shell脚本嵌套if else

您所在的位置:网站首页 shell if else if语句格式报错 shell脚本嵌套if else

shell脚本嵌套if else

2024-07-17 11:50| 来源: 网络整理| 查看: 265

【注意1】:和Java、PHP等语言不一样,sh的流程控制不可为空,如:

代码如下: [php]  view plain  copy   

在sh/bash里可不能这么写,如果else分支没有语句执行,就不要写这个else,就像这样: 

[html]  view plain  copy if condition  then      command1      command2      ...      commandN  fi  

当然,也可以写成一行(适用于终端命令提示符),像这样:

[html]  view plain  copy if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;   也就是说 [html]  view plain  copy if condition  then   也可以写成 [html]  view plain  copy if condition;then   【注意2】: if后的condition一定要是一个条件语句,其结果应该是true或false,虽然我们常常将1认为是true、0认为是false,但是这里的condition运算结果只能是true或false,否则,即使执行结果是1或0,都会认为condition这个条件是具备的,就不走其他分支了。例如: [html]  view plain  copy a=1.2  b=2.3  c=3.4  if [ 1 -eq 0 ]  then    echo aaaaaaaaaa  fi      if [ `echo "$a > $c"|bc` -ne 0 ]    then          echo "max is a"    else          echo "max is c"    fi    if [ `echo "$a > $c"|bc` ]; then          echo "max is a"    else          echo "max is c"    fi   上面这个脚本,执行结果是: max is cmax is a 这里注意到了 [html]  view plain  copy `echo "$a > $c"|bc`  与 `echo "$a > $c"|bc` -ne 0 执行的结果分别是0和false,但是if会认为结果0是true,false就是false。  

1、if格式

if [ condition ]    --注意括号两边有空格,condition 是个条件表达式then         commandsfi作用:判断 condition 条件是否成立,如果成立,执行中间的命令 commands,不成立不执行。    如: if [ $a -gt $b ]        then         echo "a大于b"            fi        if 可以接 条件表达式 (如 if [ $a -gt $b ]),也可以直接接一个命令(如 if mkdir /abc ) ,这时,会把命令的执行结果作为判断,如果成功执行,就相当于条件成立,如果执行不成功,就相当于条件不成立。

2、if else格式

[html]  view plain  copy if condition  then      command1      command2      ...      commandN  else      command  fi  

3、if else-if else格式

[html]  view plain  copy if condition1  then      command1  elif condition2      command2  else      commandN  fi  

if else语句经常与test命令结合使用,如下所示: 

[html]  view plain  copy num1=$[2*3]  num2=$[1+5]  if test $[num1] -eq $[num2]  then      echo 'The two numbers are equal!'  else      echo 'The two numbers are not equal!'  fi  

输出:The two numbers are equal!

4、if的嵌套

格式一:

  if [ condition ]  then         if [ condition ]        then             commands1        else            commands2         fi       fi格式二:

if [ condition ]then     if [ condition ]    then          commands1    else             commands2    fielse    commands3fi

5、多条件表示:

    逻辑与    if [ condition1 -a condition2 ]   或   if [ condition1 ] && [ condition2 ]    逻辑或    if [ condition1 -o condition2 ]   或   if [ condition1 ] || [ condition2 ]    逻辑非(取反)    !  

尊重原创

http://blog.csdn.net/huangjin0507/article/details/45048975



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3